<?php

namespace app\admin\controller\business;

// 引入基类控制器
use app\common\controller\Backend;

class Privatesea extends Backend
{
    // 开启数据限制
    protected $dataLimit = 'auth';
    protected $dataLimitField = 'adminid';

    protected $AdminModel;
    protected $ReceiveModel;
    protected $SourceModel;
    protected $RegionModel;

    public function __construct()
    {
        parent::__construct();

        // 加载模型
        $this->model = model('Business.Business');
        $this->AdminModel = model('Admin');
        $this->ReceiveModel = model('Business.Receive');
        $this->SourceModel = model('Business.Source');
        $this->RegionModel = model('Region');

        // 查询来源数据
        $SourceList = $this->SourceModel->column('id,name');

        $SexList = [0 => '保密', 1 => '男', 2 => '女'];

        $DealList = [0 => '未成交', 1 => '已成交'];

        $AuthList = [0 => '未认证', 1 => '已认证'];

        // 注入前置数据
        $this->view->assign([
            'SourceList' =>  $SourceList,
            'SexList' => $SexList,
            'AuthList' => $AuthList,
            'DealList' => $DealList
        ]);
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            // 过滤请求参数中的html标签和取消两边你空白
            $this->request->filter(['strip_tags', 'trim']);
            // 获取查询参数
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();

            $list = $this->model
                ->with(['source', 'admin' => ['id', 'username']])
                ->where($where)
                ->where('adminid', '<>', 'NULL')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = [
                'rows' => $list,
                'total' => $total
            ];

            return json($result);
        }

        return $this->view->fetch();
    }
    // 添加客户
    public function add($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');

            // 生成随机盐
            $salt = randstr();
            // 加密密码
            $password = md5($params['password'] . $salt);
            // 组装数据
            $data = [
                'nickname' => $params['nickname'],
                'mobile' => $params['mobile'],
                'password' => $password,
                'salt'     => $salt,
                'gender'   => $params['gender'],
                'sourceid' => $params['sourceid'],
                'email'    => $params['email'],
                'deal'     => $params['deal'],
                'adminid'  => $this->auth->id,
                'auth'     => $params['auth'],
                'money'    => $params['money'],
            ];

            // 是否选择了地区
            if(!empty($params['code'])){
                $region = $this->RegionModel
                    ->where('code', $params['code'])
                    ->value('parentpath');
                
                if(!$region){
                    $this->error('选择的地区不存在');
                }

                $paths = explode(',', $region);

                // 加入数据
                $data['province'] = $paths[0] ?? null;
                $data['city'] = $paths[1] ?? null;
                $data['district'] = $paths[2] ?? null;
            }

            // 开启事务
            $this->ReceiveModel->startTrans();
            $this->model->startTrans();

            // 插入客户表
            $busResult = $this->model
                ->validate('common/Business/Business.register')
                ->save($data);

            if(!$busResult){
                $this->error($this->model->getError());
            }

            $receivData = [
                'applyid' => $this->auth->id,
                'busid'   => $this->model->getLastInsID(), // 获取插入的客户id
                'status'  => 'allot', // 设置类型为分配
            ];

            // 插入领取表
            $receivResult = $this->ReceiveModel
                ->validate('common/Business/Receive')
                ->save($receivData);

            if(!$receivResult){
                $this->model->rollback();
                $this->error($this->ReceiveModel->getError());
            }

            if($busResult && $receivResult){
                $this->model->commit();
                $this->ReceiveModel->commit();
                $this->success('添加成功');
            }else{
                $this->model->rollback();
                $this->ReceiveModel->rollback();
                $this->error('添加失败');
            }
        }

        return $this->view->fetch();
    }
    // 编辑客户
    public function edit($ids = null){
        $row = $this->model->find($ids);

        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');

            
            // 组装数据
            $data = [
                'id'       => $ids,
                'nickname' => $params['nickname'],
                'mobile'   => $params['mobile'],
                'gender'   => $params['gender'],
                'sourceid' => $params['sourceid'],
                'email'    => $params['email'],
                'deal'     => $params['deal'],
                'auth'     => $params['auth'],
                'money'    => $params['money'],
            ];

            // 是否输入新密码
            if(!empty($params['password'])){
                // 生成随机盐
                $salt = randstr();
                // 加密密码
                $password = md5($params['password'] . $salt);
                // 加入数据
                $data['salt'] = $salt;
                $data['password'] = $password;
            }

            // 邮箱是否改变
            if($row['email'] != $data['email']){
                $data['data'] = 0; // 取消认证状态
            }

            // 是否选择了地区
            if(!empty($params['code'])){
                $region = $this->RegionModel
                    ->where('code', $params['code'])
                    ->value('parentpath');
                
                if(!$region){
                    $this->error('选择的地区不存在');
                }

                $paths = explode(',', $region);

                // 加入数据
                $data['province'] = $paths[0] ?? null;
                $data['city'] = $paths[1] ?? null;
                $data['district'] = $paths[2] ?? null;
            }

            // 更新客户表
            $busResult = $this->model
                ->validate('common/Business/Business.profile')
                ->isUpdate(true)
                ->save($data);

            if(!$busResult){
                $this->error($this->model->getError());
                exit;
            }

            $this->success();
        }


        // 处理地区数据
        $row['regionCode'] = $row['district'] ?: ($row['city'] ?: $row['province']);

        $this->view->assign("row", $row);

        return $this->view->fetch();
    }
    // 回收客户
    public function recovery($ids = null){
        if(empty($ids)){
            $this->error(__('No Results were found'));
            exit;
        }
        
        $ids = !empty($ids) ?  explode(',', $ids) : [];
        // 根据ID 查询客户信息
        $row = $this->model->whereIn('id', $ids)->column('id');

        foreach($ids as $id){
            if(!in_array($id, $row)){
                $this->error('没有找到该用户');
                exit;
            }
        }

        $receiveList = [];
        $busList = [];

        foreach($ids as $id){
            $busList[] = [
                'id' => $id,
                'adminid' => null, // 将 adminid 设置为 null 表示回收
            ];

            $receiveList[] = [
                'applyid' => $this->auth->id,
                'status' => 'recovery', // 设置状态为回收
                'busid' => $id
            ];
        }

        // 开始事务
        $this->model->startTrans();
        $this->ReceiveModel->startTrans();

        // 更新客户表
        $busResult = $this->model->isUpdate(true)->saveAll($busList);
        
        if(!$busResult){
            $this->error($this->model->getError());
        }

        // 插入领取表
        $receiveResult = $this->ReceiveModel->saveAll($receiveList);

        if(!$receiveResult){
            $this->model->rollback();
            $this->error($this->ReceiveModel->getError());
        }

        if($busResult && $receiveResult){
            $this->model->commit();
            $this->ReceiveModel->commit();
            $this->success('回收成功');
        }else{
            $this->model->rollback();
            $this->ReceiveModel->rollback();
            $this->error('回收失败');
        }
    }
    // 删除客户
    public function del($ids = null)
    {
        if(empty($ids)){
            $this->error(__('No Results were found'));
            exit;
        }
        
        $ids = !empty($ids) ?  explode(',', $ids) : [];
        // 根据ID 查询客户信息
        $row = $this->model->whereIn('id', $ids)->column('id');

        foreach($ids as $id){
            if(!in_array($id, $row)){
                $this->error('没有找到该用户');
                exit;
            }
        }

        $result = $this->model->destroy($ids);

        if ($result === false) {
            $this->error($this->model->getError());
            exit;
        }

        $this->success('删除成功');
        exit;
    }
}
